/**
 * http://usejsdoc.org/
 * @desc 文件读写 - 服务端
 */
/**首先require 加载模块*/
var http = require('http'),//web服务创建模块
	fs = require('fs'),//fs文件处理模块
	url = require('url'),//url处理模块
	querystring = require('querystring'),//字符处理模块
	httpParam = require('./http_param'),//HTTP参数获取模块
	staticModule = require('./static_module'),//静态服务器模块
	jade = require('jade'),//jade模板模块
	socket = require('socket.io');//socket模板模块
	var BASE_DIR = __dirname,
	filePath = BASE_DIR + '/version.txt';

/**
 * 创建首页函数
 * @param res http响应对象
 * @returns
 */
function defaultIndex(res){
	res.render('rw_client.jade',{'user':'devintam'});
}	

var app = http.createServer(function(req,res){
	/**为HTTP响应对象res新增jade模块解析方法*/
	res.render = function(template,options){
		var str = fs.readFileSync(template, 'utf8');
		var fn = jade.compile(str,{filename:template,pretty:true});
		var page = fn(options);
		res.writeHead( 200 , {"Content-Type":"text/html"});
		res.end(page);
	};
	
	/**获取用户url请求路径，并应用decodeURI解析url中的特殊字符和中文*/
	var pathname = decodeURI(url.parse(req.url).pathname);
	
	/**初始化httpParam模块*/
	httpParam.init(req,res);
	if('favicon.ico' === pathname){
		return;
	}
	
	switch (pathname) {
		case '/':defaultIndex(res);
			break;
		case '/index':defaultIndex(res);
			break;
		default: staticModule.getStaticFile(pathname,res,req);
			break;
	}
	
	
}).listen(8080);	


/**定义socket连接时，执行的回调操作*/
var io = socket.listen(app);
io.sockets.on('connection',function(socket){
	var message = fs.readFileSync(filePath, 'utf8');
	/**监听change_from_server消息*/
	socket.emit('change_from_server',{msg:message});
	socket.on('success',function(data){ /**监听success消息*/
		console.log(data);
	});
	
	socket.on('data',function(data){ /**监听success消息*/
		fs.writeFile(filePath,data.msg,'utf8',function(){
			socket.emit('change_from_server',{msg:data.msg});
		});
	});
});